package com.zzl.controller;

import cn.hutool.core.map.MapUtil;
import com.google.code.kaptcha.Producer;
import com.zzl.util.Const;
import com.zzl.util.RedisUtil;
import com.zzl.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @ClassName: AuthController
 * @Description: GOOD
 * @author: ZZL
 * @date: 2021/7/6  8:49
 */
@RestController
public class AuthController {

    @Autowired
    Producer producer;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    HttpServletRequest request;

    @GetMapping("/user/captcha")
    public Result captcha() {
        String key = UUID.randomUUID().toString();
        String code = producer.createText();
        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        BASE64Encoder encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";
        String base64Img = str + encoder.encode(outputStream.toByteArray());
        redisUtil.set(Const.CAPTCHA_KEY,code,120);
        return Result.succ(
                MapUtil.builder()
                        .put("captchaImg",base64Img)
                        .put("codeY",code)
                        .build()
        );
    }
}
